package com.zxtech.zzm.ftp

import android.util.Log
import com.zxtech.zzm.ftp.`interface`.FTPUploadStatusInterface
import java.io.File

class FTPUploadThread private constructor() : Thread() {
  var statusInterface: FTPUploadStatusInterface? = null

  @Synchronized
  override fun run() {
    Log.e("zzm debug", "FTPUploadThread " + this.id + " running")
    super.run()
    this.name = "FTPUploadThread"
    while (!statusInterface?.getLogUploadTasks()!!
            .isEmpty()
    ) {
      val logUploadTask: LogUploadTask = statusInterface?.getLogUploadTasks()!!
          .peek()
      val localFilePath = logUploadTask.localFilePath
      val remoteFolderPath = logUploadTask.remoteFolderPath
      try {
        FTP().uploadSingleFile(
            File(localFilePath), remoteFolderPath,
            object : FTP.UploadProgressListener {
              override fun onUploadProgress(
                currentStep: String?,
                uploadSize: Long,
                file: File?
              ) {
                when (currentStep) {
                  FTP.FTP_UPLOAD_LOADING -> {
                    val progress =
                      File(localFilePath).length()
                          .toString() + "|" + uploadSize
                    Log.e("zzm debug", localFilePath + " progress = " + progress)
                    statusInterface?.replyUploading(logUploadTask, uploadSize)
                  }
                  FTP.FTP_UPLOAD_SUCCESS -> {
                    statusInterface?.replySuccess(logUploadTask)
                    statusInterface?.getLogUploadTasks()!!
                        .poll()
                  }
                  FTP.FTP_CONNECT_FAIL, FTP.FTP_UPLOAD_FAIL -> {
                    statusInterface?.replyFail(logUploadTask)
                    statusInterface?.getLogUploadTasks()!!
                        .poll()
                  }
                  else -> {
                  }
                }
              }
            })
      } catch (e: Exception) {
        e.printStackTrace()
        statusInterface?.replyFail(logUploadTask)
        statusInterface?.getLogUploadTasks()!!
            .poll()
      }
    }
    Log.e("zzm debug", "FTPUploadThread " + this.id + " finished")
  }

  companion object {
    val instance = FTPUploadThread()
  }
}